package com.addcn.pushlibrary.xiaomi
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.util.Log
import com.addcn.pushlibrary.LConfiguration
import com.xiaomi.channel.commonutils.logger.LoggerInterface
import com.xiaomi.mipush.sdk.Logger
import com.xiaomi.mipush.sdk.MiPushClient


/**
 * author:luwenbo
 * created on date : 2019-06-06
 * content:
 * describe:
 */

class LMiManger{
    companion object{
        var TAG = "LMiManger"
        fun init(application: Application, configuration: LConfiguration?) {
            if (shouldInit(application.applicationContext)){
                MiPushClient.registerPush(application,configuration!!.xmAppId,configuration!!.xmAppKey)
            }
            val newLogger: LoggerInterface = object : LoggerInterface {
                override fun setTag(tag: String) {
                    // ignore
                }

                override fun log(content: String, t: Throwable) {
                    Log.d(TAG, content, t)
                }

                override fun log(content: String) {
                    Log.d(TAG, content)
                }
            }
            Logger.setLogger(application, newLogger)
        }

        private fun shouldInit(context: Context): Boolean {
            val am: ActivityManager? =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
            val processInfos: List<ActivityManager.RunningAppProcessInfo> =
                am!!.runningAppProcesses
            val mainProcessName: String = context.applicationInfo.processName
            val myPid: Int = android.os.Process.myPid()
            for (info in processInfos) {
                if (info.pid === myPid && mainProcessName == info.processName) {
                    return true
                }
            }
            return false
        }

        fun startPush(context: Context) {
            MiPushClient.resumePush(context,null)
        }

        fun stopPush(context: Context) {
            MiPushClient.pausePush(context,null)
        }

        fun setTag(context: Context){
            MiPushClient.setAlias(context,null,"")
        }


        fun unRegister(){
            //MiPushClient.registerToken()
        }

        fun getRegisterId(context: Context):String{
            if (MiPushClient.getRegId(context) == null){
                return ""
            }
           return MiPushClient.getRegId(context)
        }

    }

}